package com.sunshine.wrongquestionset.activity.question

import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.AppCompatRatingBar
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.card.MaterialCardView
import com.google.android.material.chip.Chip
import com.google.android.material.chip.ChipGroup
import com.google.android.material.textview.MaterialTextView
import com.sunshine.wrongquestionset.R
import com.sunshine.wrongquestionset.callback.OnClickListener
import com.sunshine.wrongquestionset.room.entity.QuestionEntity
import com.sunshine.wrongquestionset.view.HasEmptyRecyclerAdapter
import java.text.DecimalFormat
import kotlin.math.max
import kotlin.math.min

/**
 * @author sunshine
 * @date 2021/3/30
 */
class QuestionAdapter(
    private val list: List<QuestionEntity>?,
    private val callback: OnClickListener
): HasEmptyRecyclerAdapter<QuestionAdapter.ViewHolder>(list) {

    private val decimalFormat = DecimalFormat("0.##")
    private lateinit var context: Context

    inner class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
        val root: MaterialCardView = itemView.findViewById(R.id.item_question_root)
        val ratingBar: AppCompatRatingBar = itemView.findViewById(R.id.ratingBar)
        val myName: MaterialTextView = itemView.findViewById(R.id.question_name)
        val chipGroup: ChipGroup = itemView.findViewById(R.id.chipGroup)
        val info: MaterialTextView = itemView.findViewById(R.id.textView_familiarity)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        context = parent.context
        return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_question, parent, false))
    }

    override fun getItemCount(): Int {
        return list?.size?:0
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val titlePath = list!![position].titlePath
        holder.myName.text =
            if (titlePath.contains(Regex("!\\[.*]\\(.*\\)"))) "内含图片，请点击查看"
            else titlePath

        holder.ratingBar.rating = list[position].difficulty

        //添加标签
        if (!list[position].tag.isBlank()) {
            list[position].tag.split("#").forEach {
                val chip = Chip(context)
                chip.text = it
                holder.chipGroup.addView(chip)
            }
        }

        holder.info.text = "熟悉程度：${decimalFormat.format(min(1.0f, max(0.0f, list[position].familiarity)))}"

        holder.root.setOnClickListener {
            callback.onClick(position)
        }
    }
}